<?php
/**
 * View类
 */
namespace Hi;
class View{
    /**
     * 控制器
     * @var
     */
    private $_controller;
    /**
     * 动作
     * @var
     */
    private $_action;
    /**
     * Request实例
     * @var
     */
    private $_request;
    /**
     * 基础路径
     * @var
     */
    protected $_baseUrl;
    /**
     * Layout实例
     * @var
     */
    public $_layout;

    /**
     * 构造
     */
    public function __construct(){
        //1、实例化 Request类
        $this->_request = Request::getInstance();
        //2、实例化App类
        $app = App::getInstance();
        //3、获取控制器
        $this->_controller = $app->controller;
        echo $this->_controller;
        //4、获取动作
        $this->_action = $app->action;
        //5、布局模式
        if (LAYOUT_ON === true) {
            $this->_layout = Layout::getInstance();
            $this->_layout->setLayoutPath(LAYOUT_PATH);
        }
    }

    public function __set($variable, $value) {
        $this->assign($variable, $value);
    }
    /**
     * 接收来自于控制器的变量
     * @param $variable
     * @param $value
     * @return bool
     */
    public function assign($variable, $value) {
        if (substr($variable, 0, 1) != '_') {
            $this->$variable = $value;

            return true;
        }
        return false;
    }

    /**
     * 显示
     * @throws Exceptions
     */
    public function display() {
        //View层路径
        $view = APP_PATH . DS . 'View' . DS;
        $view .= strtolower($this->_controller) . DS . $this->_action . '.php';

        if (!file_exists($view)) {
            throw new Exceptions('View "' . $this->_action . '" does not exist.',404);
        }

        $content = $this->render($view);

        header('Cache-Control: ' . HTTP_CACHE_CONTROL);
        header('X-Powered-By: HiCoder');

        if (LAYOUT_ON === true) {
            $this->_layout->content = $content;
            $layoutScript = $this->_layout->getLayoutScript();
            include ($layoutScript);
        } else {
            echo $content;
        }
        die();
    }

    /**
     * 渲染器
     * @param $script
     * @param bool $check
     * @return string
     * @throws Exceptions
     */
    public function render($script, $check = true) {
        if ($check === true) {
            if (!file_exists($script)) {
                throw new Exceptions('File "' . $script . '" does not exist.',404);
            }
        }

        if (SHOW_DEBUG === false) {
            ob_end_clean();
        }

        ob_start();
        include ($script);
        $content = ob_get_contents();
        ob_end_clean();
        ob_start();

        return $content;
    }
}